<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use App\Models\Developer;
use Illuminate\Support\Facades\Cache;

class AuthController extends Controller
{
    public function getAccessToken($bn, Request $request)
    {
        $onlys = [
            'grant_type', 'client_id', 'timestamp',
            'username', 'password', 'scope', 'sign'
        ];
        $musts = [
            'grant_type', 'client_id', 'timestamp',
            'username', 'password', 'sign'
        ];
        $input = $request->only($onlys);

        if (!$request->has($musts)) {
            return response()->json([
                'success' => false,
                'result_message' => 'some parameters is null!',
            ]);
        }

        $timestamp = intval($input['timestamp']);
        $now = time();
        if ($timestamp > $now + 1800 || $timestamp < $now - 1800) {
            return response()->json([
                'success' => false,
                'result_message' => 'timestamp error!',
            ]);
        }

        if (!$this->checkSign($input)) {
            return response()->json([
                'success' => false,
                'result_message' => 'sign error!',
            ]);
        }

        $developer = Developer::where("username", $input['username'])
            ->where("password", $input['password'])
            ->first();

        if (!$developer) {
            return response()->json([
                'success' => false,
                'result_message' => 'username or password error!',
            ]);
        }

        $access_token = Str::random(25);
        $refresh_token = Str::random(40);
        $access_token_expire = $now + 3600 * 24;
        $refresh_token_expire = $now + 3600 * 24 * 30;

        $developer->access_token = $access_token;
        $developer->refresh_token = $refresh_token;
        $developer->access_token_expire = $access_token_expire;
        $developer->refresh_token_expire = $refresh_token_expire;
        $developer->save();

        Cache::put('DEV_AccToken_' . $access_token, $developer->id, $access_token_expire);
        Cache::put('DEV_RefToken_' . $refresh_token, $developer->id, $refresh_token_expire);

        return response()->json([
            'success' => true,
            'result_message' => '',
            'access_token' => $access_token,
            'refresh_token' => $refresh_token,
            'time' => $now
        ]);
    }

    function refreshToken($bn, Request $request)
    {
        $onlys = [
            'refresh_token', 'client_id'
        ];
        $input = $request->only($onlys);
        if (!$request->has($onlys)) {
            return response()->json([
                'success' => false,
                'result_message' => 'some parameters is null!',
            ]);
        }

        $developer = Developer::where("refresh_token", $input['refresh_token'])
            ->first();
        if (!$developer) {
            return response()->json([
                'success' => false,
                'result_message' => 'refresh_token error!',
            ]);
        }

        $now = time();
        $access_token = Str::random(25);
        $refresh_token = Str::random(40);
        $access_token_expire = $now + 3600 * 24;
        $refresh_token_expire = $now + 3600 * 24 * 30;

        $developer->access_token = $access_token;
        $developer->refresh_token = $refresh_token;
        $developer->access_token_expire = $access_token_expire;
        $developer->refresh_token_expire = $refresh_token_expire;
        $developer->save();

        Cache::put('DEV_AccToken_' . $access_token, $developer->id, $access_token_expire);
        Cache::put('DEV_RefToken_' . $refresh_token, $developer->id, $refresh_token_expire);

        return response()->json([
            'success' => true,
            'result_message' => '',
            'access_token' => $access_token,
            'refresh_token' => $refresh_token,
            'time' => $now
        ]);
    }

    function testSign(Request $request)
    {
        $client_secret = config('app.client_secret');

        $input = [
            'timestamp' => time(),
            'client_id' => 'huan',
            'username' => 'unicom029',
            'password' => '7573accb10ee69b5a7849dd5cbbdabde',
            'grant_type' => 'access_token',
            'scope' => ''
        ];

        $fullStr = $client_secret . $input['timestamp'] .
            $input['client_id'] . $input['username'] . $input['password'] .
            $input['grant_type'] . $input['scope'] . $client_secret;


        $url = '/api/iptv_card/cmcc/GetAccessToken?' .
            Arr::query($input) .
            '&sign=' .
            strtoupper(md5(trim($fullStr)));

        return response()->json([
            'success' => true,
            'result_message' => $url
        ]);
    }

    function checkSign($input)
    {
        $client_secret = config('app.client_secret');

        $fullStr = $client_secret . $input['timestamp'] .
            $input['client_id'] . $input['username'] . $input['password'] .
            $input['grant_type'] . $input['scope'] . $client_secret;

        return (strtoupper(md5(trim($fullStr))) ==  $input['sign']);
    }

    public static function encrypt($string, $key)
    {
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $data = strtoupper(bin2hex($data));
        return $data;
    }


    /**
     * @param string $string 需要解密的字符串
     * @param string $key 密钥
     * @return string
     */
    public static function decrypt($string, $key)
    {
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }
}
